package com.bbs.service.impl;

import com.bbs.dao.UserDao;
import com.bbs.entity.User;
import com.bbs.service.UserService;
import com.bbs.utils.MailUtils;
import com.bbs.utils.MyConstant;
import com.bbs.utils.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User findById(int id) {
        User user = userDao.findById(id);
        return user;
    }

    @Override
    public List<User> listUserByTime() {
        return userDao.listUserByTime();
    }

    @Override
    public List<User> listUserByHot() {
        return userDao.listUserByHot();
    }

    @Override
    public int register(User user) {
        // 判断邮箱是否被占用,占用返回2
        if(Objects.nonNull(userDao.findByEmail(user.getEmail()))){
            return 2;
        }
        //构造user，设置未激活
        user.setActived(0);
        String activateCode = MyUtil.createActivateCode();
        user.setActivateCode(activateCode);// 随机不能重复的激活码
        user.setJoinTime(MyUtil.formatDate(new Date()));// 注册时间
        user.setUsername("JM"+new Random().nextInt(10000)+"号");//用户名，JM+随机数
        user.setHeadUrl(MyConstant.QINIU_IMAGE_URL);//用户头像地址
        int flag = userDao.insertUser(user);//入库
        if(flag == 1){
            // 发送邮件
            String content = "<a href='http://localhost:8086/ssm_bbs_war_exploded/activate?code="+user.getActivateCode()+"'>点击激活【广西经贸】</a>";
            MailUtils.sendMail(user.getEmail(),content,"用户注册激活");
        }
        return flag;
    }

    @Override
    public void active(String code) {
        userDao.active(code);
    }

    @Override
    public User checkPassword(User user){
        User myUser = userDao.checkPassworld(user);
        return myUser;
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }


}
